package org.example;

import javax.swing.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 主神检测系统 - 控制主神的检测逻辑和警报触发
 */
public class MainDeityDetectionSystem {
    private static final int MAX_DETECTION_LEVEL = 100;
    private static final int DETECTION_THRESHOLD = 80;
    private static final int BASE_DECAY_RATE = 2;

    private int detectionLevel;
    private boolean isAlertActive;
    private final Random random;
    private final CodeRebirthGame game;

    // 检测参数配置
    private int scanFrequency = 5000;  // 基础扫描间隔(ms)
    private int anomalyWeight = 15;    // 异常操作权重
    private int speedBoost = 3;        // 警报状态加速系数

    public MainDeityDetectionSystem(CodeRebirthGame game) {
        this.game = game;
        this.random = new Random();
        startDetectionCycle();
    }

    /**
     * 启动自动检测循环
     */
    private void startDetectionCycle() {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                updateDetectionLevel();
                checkForDetection();
            }
        }, scanFrequency, scanFrequency);
    }

    /**
     * 更新检测级别（包含随机波动）
     */
    private void updateDetectionLevel() {
        // 基础衰减
        detectionLevel = Math.max(0, detectionLevel - BASE_DECAY_RATE);

        // 添加随机波动（-5到+10之间）
        detectionLevel += random.nextInt(15) - 5;

        // 玩家行为影响
        if (game.getPlayerData().getSystemHealth() < 50) {
            detectionLevel += 8;  // 低健康状态增加暴露风险
        }

        detectionLevel = Math.min(detectionLevel, MAX_DETECTION_LEVEL);
    }

    /**
     * 检查是否需要触发警报
     */
    private void checkForDetection() {
        if (detectionLevel >= DETECTION_THRESHOLD && !isAlertActive) {
            triggerAlertSequence();
        }
    }

    /**
     * 触发警报序列
     */


    private void triggerAlertSequence() {
        isAlertActive = true;
        scanFrequency /= speedBoost;
        SwingUtilities.invokeLater(() -> {
            try {
                // 双重检查锁定确保线程安全
                GameState current = game.getCurrentState();
                if (current == null || !current.getClass().equals(AlertState.class)) {
                    synchronized (game) {
                        current = game.getCurrentState();
                        if (current == null || !current.getClass().equals(AlertState.class)) {
                            game.changeState(new AlertState(game));
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("状态切换错误: " + e.getMessage());
                e.printStackTrace();
            }
        });
    }
    /**
     * 处理玩家操作事件
     * @param eventType 事件类型（1=代码错误 2=快速操作 3=使用提示）
     */
    public void logPlayerAction(int eventType) {
        switch (eventType) {
            case 1: // 代码错误
                detectionLevel += anomalyWeight * 2;
                break;
            case 2: // 快速操作（2秒内超过5次操作）
                detectionLevel += anomalyWeight;
                break;
            case 3: // 使用提示
                detectionLevel += anomalyWeight / 2;
                break;
        }

        // 添加随机扰动
        detectionLevel += random.nextInt(10);
        detectionLevel = Math.min(detectionLevel, MAX_DETECTION_LEVEL);
    }

    /**
     * 重置检测系统（当完成干扰挑战后调用）
     */
    public void resetDetectionSystem() {
        detectionLevel = 0;
        isAlertActive = false;
        scanFrequency = 5000;
    }

    // ======== 状态获取方法 ========
    public int getDetectionLevel() {
        return detectionLevel;
    }

    public String getDetectionStatus() {
        if (detectionLevel > DETECTION_THRESHOLD) {
            return "紧急警报！主神正在接近！";
        }
        return String.format("系统扫描强度：%d%%", detectionLevel);
    }

    public boolean isUnderAlert() {
        return isAlertActive;
    }

    // ======== 难度调节方法 ========
    public void increaseDifficulty() {
        anomalyWeight += 2;
        speedBoost++;
        scanFrequency = Math.max(1000, scanFrequency - 500);
    }

    public void decreaseDifficulty() {
        anomalyWeight = Math.max(5, anomalyWeight - 1);
        speedBoost = Math.max(1, speedBoost - 1);
        scanFrequency += 500;
    }
}